<?php

namespace app\index\model;

use think\facade\Db;
use think\facade\Session;
use think\Model;

class PayedArt extends Model
{
    // 文章付费
   static public function pay($art_id)
    {
        $uid = Session::get('user.user_id');
        $isHas = self::where(['user_id' => $uid ,'article_id' => $art_id])->findOrEmpty();
        if(!$isHas) return '无需重复支付该文章哦！';
        // 判断积分是否足够
        $userScore = User::where('id', $uid)->value('score');
        $needScore = Article::where('id', $art_id)->value('score');
        if ($userScore >= $needScore)     $score = $userScore - $needScore;
        else{
            $needScore = $needScore - $userScore;
            return "支付失败：当前余额积分仅有[ $userScore ] ,还需[ $needScore ]积分";
        }
        $data = [
            'article_id' => $art_id,
            'user_id' => $uid
        ];
        $res = self::create($data);
        User::where('id' , $uid)->update(['score' => $score]);
        if ($res) return 1;
        else return 0;
    }
}
